<template>
  <el-form ref="form" :rules="rules" :model="formData" label-width="80px">
  <el-form-item label="所属学科" prop="subjectID" >
    <el-select v-model="formData.subjectID" placeholder="请选择" style="width: 100%;">
      <el-option v-for="item in directorysData" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="目录名称" prop="directoryName">
    <el-input v-model="formData.directoryName" placeholder="请输入目录名称"></el-input>
  </el-form-item>
  <el-form-item>
      <el-button @click="addCancel">取消</el-button>
      <el-button type="primary" @click="addSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/directorys'
import { simple as getSubjects } from '@/api/hmmm/subjects'
export default {
  name: 'addDialog',
  data () {
    return {
      directorysData: [],
      formData: {
        subjectID: '',
        directoryName: ''
      },

      // 表单校验
      rules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'change' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'change' },
          { min: 1, message: '请输入目录名称', trigger: 'change' }
        ]
      }
    }
  },
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },

    parentId: {
      type: [Object, String],
      required: true
    }
  },
  created () {
    this.getSubjects()

    this.getDirecDetail()
  },

  methods: {
    // 根据id获取目录详情
    async getDirecDetail () {
      if (this.isEdit) {
        const res = await detail(this.parentId)
        // console.log(res.data)
        this.formData.subjectID = res.data.subjectID
        this.formData.directoryName = res.data.directoryName
      }
    },

    // 编辑
    async editDirectory () {
      const res = await update({ ...this.formData, id: this.parentId.id })
      // console.log(res)
      if (res.status === 200) {
        // 给用户提示
        this.$message.success('操作成功')
      }
      // 更新目录列表，隐藏弹框
      this.$emit('update')
    },

    // 新增
    async addDirectory () {
      const res = await add(this.formData)
      // console.log(res)
      if (res.status === 200) {
        // 给用户提示
        this.$message.success('操作成功')
      }
      // 更新目录列表，隐藏弹框
      this.$emit('update')
    },

    // 获取学科详情
    async getSubjects () {
      const res = await getSubjects()
      // console.log(res.data)
      this.directorysData = res.data
    },

    // 点击取消
    addCancel () {
      this.$emit('close')
    },

    // 提交表单
    addSubmit () {
      // 兜底验证
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.isEdit ? this.editDirectory() : this.addDirectory()
        }
      })
    }
  }
}
</script>

<style scoped>
 ::v-deep .el-form-item__content{
   margin-left: 200px;;
 }
</style>
